<template>
  <div class="app-container">
    <div class="card-box">
      <el-button type="primary" @click="handleToAdd">添加字段</el-button>
    </div>
    <div class="card-box">
      <el-table v-loading="fieldStore.loading.list" :data="fieldStore.list">
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="key" label="关键词" />
        <el-table-column prop="value" label="字段值" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="is_public" label="是否公开配置">
          <template #default="scope">
            <el-tag v-if="scope.row.is_public" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="是否启用">
          <template #default="scope">
            <el-tag v-if="scope.row.is_active" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleToEdit(row)">编辑</el-button>
            <el-popconfirm title="是否继续删除" @confirm="handleDelte(row)">
              <template #reference>
                <el-button type="danger" link size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="params.page"
        v-model:page-size="params.size"
        style="margin-top: 10px"
        background
        :total="fieldStore.totalCount"
        @change="fieldStore.fetchFieldList(params)"
      />
    </div>
    <Form
      v-model="visible"
      :type="formType"
      :form="currentRow!"
      @confirm="fieldStore.fetchFieldList(params)"
    />
  </div>
</template>

<script setup lang="ts">
import { useFieldStoreHook } from "@/store/modules/system/field";
import Form, { type FormType } from "./components/form.vue";
import { FieldListParams, FieldType } from "@/api/system/field";

const fieldStore = useFieldStoreHook();

const visible = ref(false);

const formType = ref<FormType>("add");

const currentRow = ref<FieldType | null>(null);

const params = reactive<FieldListParams>({
  page: 1,
  size: 10,
});

function handleToAdd() {
  formType.value = "add";
  visible.value = true;
}

function handleToEdit(row: FieldType) {
  formType.value = "edit";
  currentRow.value = row;
  visible.value = true;
}

async function handleDelte(row: FieldType) {
  await fieldStore.fetchDeleteField(row.id);
  await fieldStore.fetchFieldList(params);
}

onMounted(() => {
  fieldStore.fetchFieldList(params);
});
</script>

<style lang="scss" scoped></style>
